package com.briup.ch10;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/13
 * @Description:
 */
//一个生产者，两个消费者，操作的是同一张桌子，这个桌子中最多只有两个包子

class Table{
    public int num=0;
}
class Producter2 extends Thread{
    private Table table;

    public Producter2(String name, Table table) {
        super(name);
        this.table = table;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            synchronized (this.table) {
                //如果有包子，等待
                while (this.table.num > 0) {
                    System.out.println("有包子等待别人吃");
                    try {
                        this.table.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //如果没有包子，生产，通知其他人
                this.table.num+=2;
                System.out.println("生产了2个包子");
                this.table.notifyAll();
            }
        }
    }
}
class Custormer2 extends Thread{
    private Table table;

    public Custormer2(String name, Table table) {
        super(name);
        this.table = table;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            synchronized (this.table) {
                //没有包子，等待
                if(this.table.num<=0){
                    System.out.println(this.getName()+"没有包子，等待");
                    try {
                        this.table.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(this.table.num>0) {
                    //有包子，吃包子，通知
                    this.table.num--;
                    System.out.println(this.getName() + "吃了一个包子还剩:" + this.table.num);
                    this.table.notifyAll();
                }
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Test12 {
    public static void main(String[] args) {
        Table table=new Table();
        Thread p=new Producter2("师傅",table);
        Thread c1=new Custormer2("张三",table);
        Thread c2=new Custormer2("李四",table);
        p.start();
        c1.start();
        c2.start();
    }
}
